package websocket;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

import java.io.IOException;

@WebSocket
public class BroadcastHandler {

    @OnWebSocketConnect
    public void connected(Session session) {
        TalkWithServerHandler.userMap.put(session,"User" + TalkWithServerHandler.userId++);
    }

    @OnWebSocketClose
    public void closed(Session session, int statusCode, String reason) {
        TalkWithServerHandler.userMap.remove(session);
    }

    /**
     * 用户发的消息，广播给全部用户
     * @param session
     * @param message
     */
    @OnWebSocketMessage
    public void broadcast(Session session, String message) {
        try {
            String userStr = TalkWithServerHandler.userMap.get(session);
            System.out.println("User: " + userStr);
            System.out.println("Message: " + message);
            for (Session session1 : TalkWithServerHandler.userMap.keySet()) {
                session1.getRemote().sendString("【" + userStr + "】：" + message);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
